package jdbmaplite.connection.impl;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import jdbmaplite.connection.DBConnectionFactory;

import org.apache.commons.dbcp.BasicDataSource;

public class DBCPConnectionFactory extends DBConnectionFactory {

	private BasicDataSource connectionPool = null;

	/**
	 * Default constructor.
	 * 
	 * @param driver
	 *            String
	 * @param url
	 *            String
	 * @param user
	 *            String
	 * @param password
	 *            String
	 * @throws PropertyVetoException
	 */
	public DBCPConnectionFactory(String driver, String url, String user,
			String password) throws PropertyVetoException {
		super(driver, url, user, password);
		connectionPool = new BasicDataSource();
		connectionPool.setDriverClassName(driver);
		connectionPool.setUrl(url);
	}

	public void loadProperties(Properties properties) throws SQLException {
		properties.remove("driverClassName");
		properties.remove("url");
		properties.setProperty("username", getUser());
		properties.setProperty("password", getPassword());
		for (Object propertyName : properties.keySet()) {
			String propertyNameStr = (String) propertyName;
			connectionPool.addConnectionProperty(propertyNameStr,
					properties.getProperty(propertyNameStr));
		}
	}

	public Connection getConnection() throws SQLException {
		return connectionPool.getConnection();
	}

	public void destroy() throws SQLException {
		connectionPool.close();
	}

	/**
	 * Get ConnectionPool
	 * 
	 * @return BasicDataSource
	 */
	public BasicDataSource getConnectionPool() {
		return connectionPool;
	}

	/**
	 * Set ConnectionPool
	 * 
	 * @param connectionPool
	 *            BasicDataSource
	 */
	public void setConnectionPool(BasicDataSource connectionPool) {
		this.connectionPool = connectionPool;
	}

}